import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/3 14:27
 * @description 二分查找
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] c = {4,7,5};
        solution.maximumCandies(c, 4);
    }
    public int maximumCandies(int[] candies, long k) {
        // 确定查找区间
        long sum = 0;

        for (int c: candies)  { sum += c; }
        if (sum < k) { return 0; }

        long left = 1, right = sum;
        long ans = 0;

        // 二分查找
        while (left <= right) {
            long mid = left + (right - left) / 2;

            if (check(candies, mid, k)) {
                ans = mid;
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return (int) ans;
    }
    public boolean check(int[] candies, long limit, long k) {
        for (int val : candies) {
            if (val < limit) {
                continue;
            } else if (val == limit) {
                k--;
            } else {
                k -= val / limit;
            }
        }
        return k <= 0;
    }
}
